import {ElMessage, ElNotification} from "element-plus";
import {h, ref} from "vue";
const downloadProgress=ref(0)
/**
 * 流式下载
 * @param fileName 文件名
 */
export  const  streamDownLoad= async (fileName:string) => {
    const url = '/api/common/streamDownload?fileName=' + fileName;

    let downloadedSize = 0;
    // 检查本地是否有已下载的部分
    const existingBlob = localStorage.getItem(fileName);
    if (existingBlob) {
        downloadedSize = JSON.parse(existingBlob).size;
    }
    try {
        const response = await fetch(url, {
            headers: {
                Range: `bytes=${downloadedSize}-`, // 请求从已下载位置继续
            },
        });
        if (!response.ok) {
            throw new Error('下载失败');
        }


        // 获取文件总大小
        const contentRange = response.headers.get('content-range');
        const totalSize = parseInt(contentRange.split('/')[1], 10);
        const reader = response.body.getReader();
        const chunks = [];
        showTip(fileName)
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            chunks.push(value);
            downloadedSize += value.length;
            //计算下载进度
            downloadProgress.value = Math.floor((downloadedSize / totalSize) * 100);
            // 将已下载的部分保存到本地存储
            localStorage.setItem(fileName, JSON.stringify({ size: downloadedSize }));
        }
        // 将所有块组装成一个 Blob 对象
        const blob = new Blob(chunks);
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        link.remove();
        URL.revokeObjectURL(link.href);
        // 下载完成后清除本地存储
        localStorage.removeItem(fileName);
        ElMessage.success('下载完成');
    } catch (error) {
        ElNotification.closeAll();
        ElMessage.error('下载过程中出现错误');
        console.error('下载失败:', error);
    } finally {
    }
};
const    showTip=(fileName)=> {
    const contents = []
    const msg = h('p', {class:{"progress-title":true}}
        , downloadProgress.value===100?"下载完成":'文件正在下载，当前进度：'+downloadProgress.value+'%')
    const progress = h(
        'div',
        {
            class: {
                'el-progress-plus': true
            },
            style: {
                'width': '230px',
                'height': '6px',
                'background-color': '#5e7ce0',
                'margin-top': '6px',
                'border-radius': '6px',
            },
            percentage: 0,
            indeterminate:true
        },
        ''
    )
    const br = h('p', {style: 'width: auto; height: 10px'}, '')
    contents.push(msg)
    contents.push(progress)
    contents.push(br)

    let className = 'el-notification-plus' + fileName
    // 判断是否已存在该通知元素，以及最多限制生成100个通知
    if (document.getElementsByClassName(className)[0]) {
        console.log('已存在该通知元素，删除后重新创建');
        return
    }
    // 实例化通知
  const notifyInstance=  ElNotification({
        title:"下载通知",
        type: 'success',
        customClass: className,
        message: h('div', {}, contents),
        duration: 0
    })
    const timer = setInterval(() => {
        try {
            if (notifyInstance) {
                const ElNotificationPlus = document.getElementsByClassName(className)[0]
                const ElProgressPlus = ElNotificationPlus.getElementsByClassName('el-progress-plus')[0]

                const Title=document.getElementsByClassName(" progress-title")[0]
                // console.log('ElProgressPlus =>', ElProgressPlus)

                let percentage: string | null = ElProgressPlus.getAttribute('percentage')
                if (percentage <100) {
                    percentage = downloadProgress.value
                    ElProgressPlus.setAttribute('percentage', percentage)
                    Title.innerHTML=downloadProgress.value===100?"下载完成":'文件正在下载，当前进度：'+downloadProgress.value+'%'
                    ElProgressPlus.style.width = (230 * (percentage / 100)) + 'px'
                } else {

                    // 清除定时器
                    clearInterval(timer)
                    // 手动关闭通知
                    setTimeout(() => {
                        notifyInstance.close()
                        downloadProgress.value=0
                    }, 5000);
                }
            } else {
                // 清除定时器
                clearInterval(timer)
            }
        } catch (error) {
            // 清除定时器
            clearInterval(timer)
        }
    }, 50)

}